package com.demo.rocketmq.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class DemoTransactionConsumerListener implements TransactionListener {



    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        log.info("====== 执行事务 ======");
        String body = new String(msg.getBody());
        String key = msg.getKeys();
        String transactionId = msg.getTransactionId();
        log.info("transactionId=" + transactionId + ", key=" + key + ", body=" + body);
        // TODO 执行本地事务，成功则投递给消费者，失败则回滚
        if(true){
            log.info("执行本地事务成功");
            // 将本地事务执行状态放入缓存30分钟用于回查使用
            // redis.setEx(transactionId, 1);
            return LocalTransactionState.COMMIT_MESSAGE;
        }else {
            log.info("执行本地事务失败");
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {

        log.info("====== 回查事务 ======");
        String body = new String(msg.getBody());
        String key = msg.getKeys();
        String transactionId = msg.getTransactionId();
        log.info("transactionId=" + transactionId + ", key=" + key + ", body=" + body);
        // 可以根据key比如订单号去检查本地事务消息是否完成，完成返回commit，失败返回rollback
        // int value = redis.get(transactionId);
        int value = 1;
        if(value == 1){
            log.info("回查本地事务状态为成功");
            return LocalTransactionState.COMMIT_MESSAGE;
        }else {
            log.info("回查本地事务状态为失败");
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
    }
}
